import config from "../config";
import router from "../router";
import store from "../store";
let axios = require("axios");

let handleError = e => {
  if (e.response) {
    if (e.response.body) {
      return Promise.reject({
        message: e.response.body
      });
    } else if (e.response.data) {
      return Promise.reject({
        message: e.response.data.message ? e.response.data.message : "发生错误"
      });
    }
  } else {
    return Promise.reject(e);
  }
};

export default {
  get(path, params) {
    if (!params) {
      params = {};
    }
    params.token = store.state.userInfo.token;
    return axios
      .get(config.server + path, { params })
      .then(result => {
        if (result.data.success) {
          return result.data;
        } else if (result.data.code == "notlogin") {
          store.commit("logout");
          router.replace("/Login");
          return Promise.reject({
            message: result.data.message
          });
        } else {
          return Promise.reject({
            message: result.data.message ? result.data.message : "未知错误"
          });
        }
      })
      .catch(handleError);
  },
  post(path, params) {
    return axios
      .post(config.server + path, {
        token: store.state.userInfo.token,
        data: params
      })
      .then(result => {
        if (result.data.success) {
          return result.data;
        } else if (result.data.code == "notlogin") {
          store.commit("logout");
          router.replace("/Login");
          return Promise.reject({
            message: result.data.message
          });
        } else {
          return Promise.reject({
            message: result.data.message ? result.data.message : "未知错误"
          });
        }
      })
      .catch(handleError);
  }
};
